package com.gxa.springboot229.util;

import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liwen
 * @date 2020/9/30 10:41
 */
@RestController
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
      /*  TODO
  如果代码中有该标识，说明在标识处有功能代码待编写，待实现的功能在说明中会简略说明。

        FIXME: + 说明：
  如果代码中有该标识，说明标识处代码需要修正，甚至代码是错误的，不能工作，需要修复，如何修正会在说明中简略说明。

eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIiLCJpZCI6bnVsbCwiZ…3dCJ9.USGwPAckheIGV58WEUeYnu8f1S3TvZ4rTlo-2u0OBNw
：*/
        // 需要工具类JWTUtil来解析前端的请求头: Authorization
        JWTUtil util = new JWTUtil();
        String jwt = request.getHeader("Authorization");

        try {
            if (jwt == null) {
                System.out.println("请求头为空, 验证失败");
            } else {
                Claims c;
                c = util.parseJWT(jwt);
                // 通过Claim对象,可以获取在jwt中保存的特征(Map)
                System.out.println("id为" + c.get("id") + "的用户已是登录状态");
                //返回true表示放行
                return true;
            }
            System.out.println("token解析错误，验证失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 当返回false的时候, 表示被拦截住,没法访问controller
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
